
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as Actions from '../../actions/cart'
import { Checkbox,SwipeAction,Modal} from 'antd-mobile';
import Container from '../../components/Container'
import OrderProductItem from '../../components/OrderProductItem'
import MeScrollContainer from '../../components/MeScroll'
import * as utils from '../../utils'
const prompt = Modal.prompt;

class Cart extends Component{
  static contextTypes={
    router:PropTypes.object.isRequired,
  }
  constructor(props) {
    super(props);
  
    this.state={
      allCheck:false,
      showNumIndex:-1,
      
    }
  }
  componentDidMount(){
    let {actions} =this.props 
    actions.getCartList()
  }

  //单个商品checkbox
  onChangeBox(id) {
    let { cartList,actions } =this.props 
    let item = cartList.find(item => item.cart_id == id)
    item.checked=!item.checked
    this.setState({
      allCheck:cartList.filter(item => item.checked).length== cartList.length
    })
    actions.updateCartList(cartList)
  }

  deleteGoods(id){
    let {actions} =this.props
    utils.dialog.show({
        title:'Remove item',
        message : 'Are you sure you want to remove this item?',
        btnTxt:'REMOVE',
        cancelTxt:'CANCEL',
        ok : ()=>{
          actions.delOneCart({cart_id:id})
          // cartList=cartList.filter(liem => liem.cart_id != item.cart_id)
          // actions.updateCartList(cartList)
        },
        cancel:true,
        cancelCb:()=>{
         
        }

      })
    
  }
  //全选/全不选
  onChangeAllBox(){
    let {allCheck} =this.state
    let { cartList,actions } =this.props 
    cartList.map(item =>{
      return item.checked=!allCheck
    })
    this.setState({
      allCheck:!allCheck
    })
    actions.updateCartList(cartList)
  }
  submit(){
    let { cartList,actions } =this.props 
    let selectedList=cartList.filter(item => item.checked)
    if(selectedList.length<=0){
      utils.msg({text:'Please choose the goods you buy first',code:0})
      return
    }
     //this.context.router.history.push('/address/edit/0')
    this.context.router.history.push('/order/confirmation')
  }
 

  //修改主商品数量
  changeGoodsNum(item,num){
    let { cartList,actions} =this.props 
    
     actions.changeCartNum({ cart_id:item.cart_id,goods_num:item.num},{callback:(res) =>{
      if(res.code ==200){
          let _item=cartList.find (liem => liem.cart_id == item.cart_id)
          _item.goods_num=num
        actions.updateCartList(cartList)
      }
    }})
    
    //修改数量
    //num_type 增加或减少数量(0:增加数量  1:减少数量),默认是增加数量
    // actions.changeNum({ cart_id:item.cart_id,num_type:item.goods_num>num?1:0},{callback:(res) =>{
    //   if(res.code ==200){
    //       let _item=cartList.find (liem => liem.cart_id == item.cart_id)
    //       _item.goods_num=num
    //     actions.updateCartList(cartList)
    //   }
    // }})
    

   
  }
  deleteGiftGoods(pid,cid){
    utils.dialog.show({
        title:'tip',title:'Remove item',
        message : 'Are you sure you want to remove this item?',
        btnTxt:'REMOVE',
        cancelTxt:'CANCEL',
        ok : ()=>{
          actions.delExchange({cart_id:pid,exchange_cart_id:cid})
          // cartList=cartList.filter(liem => liem.cart_id != item.cart_id)
          // actions.updateCartList(cartList)
        },
        cancel:true,
        cancelCb:()=>{
         
        }

    })
  }
  //修改附属商品的数量
  changeGiftGoodsNum(item,gitem,num){
    let { cartList,actions} =this.props 
    actions.changeCartNum({ cart_id:item.cart_id,exchange_cart_id:gitem.cart_id,goods_num:item.goods_num},{callback:(res) =>{
      if(res.code ==200){
          let _item=cartList.find (liem => liem.cart_id == item.cart_id)
          _item=_item.gift_list.find(liem => liem.cart_id == gitem.cart_id)
          _item.goods_num=num
        actions.updateCartList(cartList)
      }
    }})
    
    //修改数量
    //num_type 增加或减少数量(0:增加数量  1:减少数量),默认是增加数量
    // actions.changeNum({ cart_id:item.cart_id,exchange_cart_id:gitem.cart_id,num_type:item.goods_num>num?1:0},{callback:(res) =>{
    //   if(res.code ==200){
    //       let _item=cartList.find (liem => liem.cart_id == item.cart_id)
    //       _item=_item.gift_list.find(liem => liem.cart_id == gitem.cart_id)
    //       _item.goods_num=num
    //     actions.updateCartList(cartList)
    //   }
    // }})
  }
  showNum(index){
    this.setState({
      showNumIndex:index
    })
  }
  showNumModal(num,item){
    prompt('Enter Quantity', '', [
      { text: 'Cancel' },
      { text: 'Save', onPress: value => {
        this.changeGoodsNum(item,value)

      }},
    ], 'default', num)
  }
  onClose = key => () => {
   this.setState({
    [key]:false,
    selectedItem:null
   })
  }
  onOpen(key,item){
    this.setState({
      [key]:true,
      selectedItem:item
     })
  }
  setCartStatus(id,goods_name,status){
    let { cartList,actions} =this.props 
     actions.setCartStatus({ cart_id:id,status},{callback:(res) =>{
      if(res.code ==200){
        if(status ==1 ){
           msg.info(`${goods_name} has been saved for later`,1)
        }else{
          msg.info(`${goods_name} has been moved to your cart`,1)
        }
          let _item=cartList.find (liem => liem.cart_id == id)
          _item.status=status
        actions.updateCartList(cartList)
      }
    }})
  }
  
  renderSelectNum(num,row){
    num=parseInt(num)
    let array=[1,2,3,4,5]
    if(num >3){
      array=[num-2,num-1,num,num+1,num+2]
    }
    return(
      <div className='select-num-ul'>
      {
        array.map((item,i) =>(
        <div key={i} className={item==num ?'li active':"li"} onClick={ this.changeGoodsNum.bind(this,row,item)}>{item}</div>
        ))
      }
      <div className='li' onClick={this.showNumModal.bind(this,num,row)}>More</div>
      </div>
      )
  }
  renderModel_offer(){
    let {visible,selectedItem} =this.state
    if(!selectedItem) return null
    return(
       <Modal
          popup
          visible={visible}
          onClose={this.onClose('visible')}
          animationType="slide-up"
          className='offer-model'
          
        >
        <div className='t-title'>
          <i className='iconfont icon-guanbi-01' onClick={this.onClose('visible')}></i>
          <span>Price Details</span>
        </div>
        <div className='t-box'>
        <div className='t-price'>
          <div className='item'>
            <span className='s1'>Selling Price</span>
            <span className='s2'>{selectedItem.goods_price}</span>
          </div>
          <div className='item'>
            <span className='s1'>Quantity</span>
            <span className='s2'>{selectedItem.goods_num}</span>
          </div>
          <div className='bitem'>
            <span className='s1'>Total</span>
            <span className='s2'>{utils.accMul(selectedItem.goods_num||1,selectedItem.goods_price||0)}</span>
          </div>
        </div>
        <div className='t-content'> 
          <div className='t-name'>Offer  available</div>
          <div className='t-detail'>The integral is worth  <span className='value'>${selectedItem && selectedItem.goods_use_score}</span></div>
          <div className='t-detail'>After the purchase of <span className='value'>{selectedItem && selectedItem.goods_return_score}</span>  points</div>
        </div>
        </div>
        </Modal>
      )
  }
  renderModel_unselcected(){
    let { cartList } =this.props 
    let un_selectedList=cartList.filter(item => item.status == 0)
    let {visible2} =this.state
    return(
       <Modal
          popup
          visible={visible2}
          onClose={this.onClose('visible2')}
          animationType="slide-up"
          className='offer-model unselected-model'
          
        >
        <MeScrollContainer id={'mescroll_2'}>
        <div className='t-title'>
          <i className='iconfont icon-guanbi-01' onClick={this.onClose('visible2')}></i>
          <span>Saved For Later ({un_selectedList.length})</span>
        </div>
        <div className='unbox'>
          {
            un_selectedList.map((item, index) => (
              <div className='CartItems_Container' key={index} 
              >
                { this.renderItem(item,index,false)}
              </div>
              ))
          }
          </div>
          </MeScrollContainer>
        </Modal>
      )
  }
  renderItem(item,index,isChecked){
    let { showNumIndex } =this.state
    return(
      <div className='box'>
                  <div className='top-box'>
                    <div className='d1'>
                      <div className='left-name'>
                        <div className='goods-name line-clamp-1'>{item.goods_name}</div>
                        <div className='goods-sub-name line-clamp-2'>{item.spec_str}</div>
                        {
                          isChecked?
                          <block>
                            {
                              item.goods_return_score && item.goods_use_score?
                              <div className='goods-offer' onClick={ this.onOpen.bind(this,'visible',item)}>2  Offers  Available</div>:null
                            }
                            {
                              item.goods_return_score && !item.goods_use_score?
                              <div className='goods-offer' onClick={ this.onOpen.bind(this,'visible',item)}>1  Offer  Available</div>:null
                            }
                            {
                              !item.goods_return_score && item.goods_use_score?
                              <div className='goods-offer' onClick={ this.onOpen.bind(this,'visible',item)}>1  Offer  Available</div>:null
                            }
                          </block>
                          :null
                        }
                        
                        
                      </div>
                      <div className='right-img' onClick={()=>{ this.context.router.history.push(`/goods/${item.goods_id}`)}}>
                        <img src={item.goods_image} className='img'/>
                      </div>
                    </div>
                    <div className='d2'>
                      <div className='goods-price'>
                        <span className='n-price'>${item.goods_price}</span>
                      </div>
                      {
                        isChecked?
                        <div className='goods-num' onClick={this.showNum.bind(this,index)}>
                        <div className='qty'>Qty:</div>
                        <div className='num'>{item.goods_num}</div>
                        <div className='triangle_box'><i className='triangle'></i></div>
                        {
                          showNumIndex ==index ?
                           this.renderSelectNum(item.goods_num,item):null
                        }
                        
                      </div>
                      :
                      <div className='goods-num'>
                        <div className='qty' style={{ 'textAlign':'center'}}>Qty:{item.goods_num}</div>
                      </div>
                      }
                      
                    </div>
                    <div className='d3'>Free delivery</div>
                  </div>
                  <div className='bott-box'>
                  {
                    
                    isChecked?
                    <div className='cbtn' onClick={ this.setCartStatus.bind(this,item.cart_id,0)}>
                      <i className='iconfont icon-iconset0153'></i>
                      <span className='txt'>Save for later</span>
                    </div>
                    : 
                    <div className='cbtn' onClick={ this.setCartStatus.bind(this,item.cart_id,1)}>
                      <i className='iconfont icon-gouwuche01'></i>
                      <span className='txt'>Save for later</span>
                    </div>
                  }
                   
                    <div className='cbtn' onClick={ this.deleteGoods.bind(this,item.cart_id)}>
                      <i className='iconfont icon-shanchu'></i>
                      <span className='txt'>Remove</span>
                    </div>
                  </div>
                </div>
      )
  }
  render(){
    let { showNumIndex } =this.state
    let { cartList } =this.props 
    let selectedList=cartList.filter(item => item.status == 1)
    let un_selectedList=cartList.filter(item => item.status == 0)
    var sum = selectedList.reduce(function(prev, cur) {
        return (cur.goods_num * cur.goods_price) + prev;
    }, 0);

    return(
      <Container className='cart-container'>
        <MeScrollContainer  id={'mescroll_1'}>
          <section onClick={(e)=>{if(showNumIndex>-1)
              {
                this.setState({ showNumIndex: -1}); e.stopPropagation()
              } }}>
          {
            selectedList.map((item, index) => (
              <div className='CartItems_Container' key={index} 
              >
                { this.renderItem(item,index,true)}
              </div>
              ))
          }
          {
            selectedList.length==0?
            <div className='empty-box'>
              <img src={require('../../assets/images/empty.png')} className='img' />
              <div className='e-title'>Your Cart is empty!</div>
              <div className='e-txt'>It’s a good day to buy the items you saved for later!</div>
            </div>
            :null
          }

          <div className='out-cart-tip'>
            <i className='iconfont icon-iconset0153'></i>
            <span className='txt'>You have {un_selectedList.length} products  saved for later</span>
            <span className='t-btn' onClick={this.onOpen.bind(this,'visible2')}>show</span>
          </div>

          <div className='cart-info-box'>
            <div className='t-title'>PRICE DETAILS</div>
            <div className='t-center'>
              <div className='item'>
                <span className='s1'>Price ({selectedList.length} items）</span>
                <span className='s2'>${sum}</span>
              </div>
              <div className='item'>
                <span className='s1'>Delivery</span>
                <span className='s2 red'>free</span>
              </div>
              <div className='bitem'>
                <span className='s1'>Amount Payable</span>
                <span className='s2 '>${sum}</span>
              </div>
            </div>
          </div>
          
          <div className='cart-bottom'>
            <div className='box'>
              <span className='s1'>${sum}</span>
              <span className='s2'><span onClick={()=>{selectedList.length ?this.submit :''}} 
              className={selectedList.length>0?'btn':'disabled-btn btn'}>CONTINUE</span></span>
            </div>
          </div>
          </section>
        </MeScrollContainer>

        { this.renderModel_offer()}
        { this.renderModel_unselcected()}
      </Container>
      )
  }


_render(){
    let { cartList } =this.props 
    let selectedList=cartList.filter(item => item.checked)
    var sum = selectedList.reduce(function(prev, cur) {
        return (cur.goods_num * cur.goods_price) + prev;
    }, 0);

    return(
      <Container className='cart-container'>
        <MeScrollContainer>
        {
        cartList.map((item, index) => (
            <SwipeAction
                key={index}
                className='cart-swipe-action'
                right={[
                    {
                        text: '删除',
                        onPress: () => this.deleteGoods(item.cart_id),
                        style: {backgroundColor: '#F4333C', color: 'white',padding:"0 10px"},
                    }
                ]}

                onOpen={() => console.log('global open')}
                onClose={() => console.log('global close')}
            >
            <OrderProductItem item={item} 
            onClickLeft={(e)=>{e.stopPropagation; this.context.router.history.push(`/goods/${item.goods_id}`) }}
            onChangeBox={(cart_id)=>{this.onChangeBox(cart_id)}}
            changeGoodsNum={(num)=>{this.changeGoodsNum(item,num)}} 
            changeGiftGoodsNum={(gitem,num)=>{this.changeGiftGoodsNum(item,gitem,num)}}
            onClick_gift={(id,type,e) =>{ e.stopPropagation; this.context.router.history.push(`/subGoods/${id}/${type}`) }}
            />
             
            </SwipeAction>
        ))
    }
    </MeScrollContainer>

      <div className="bottom bordertop">
        <div className='cart-left'>
          <Checkbox className='item-left' checked={this.state.allCheck} onChange={this.onChangeAllBox.bind(this)}/>
          <label>Select all</label>
        </div>
        <div className='cart-rigth'>
          <span className='all-money'>Real payment: ${sum}</span>
          <div className="del-btn" onClick={this.submit.bind(this)}> to pay </div>
        </div>
        
      </div>

      </Container>
      )
  }
  

}


function mapStateToProps(state){
  return {
    cartList:state.cartList.toJS()
  }
}
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  }
}
export default  connect(
  mapStateToProps,
  mapDispatchToProps
)(Cart)
